package fi.helsinki.cs.ohtu10k.view;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;

import org.joda.time.DateTime;

/**
 * Class implementing a simple graphical date selector using JComboBoxes. 
 * @author Thomas Nyman
 *
 */
@SuppressWarnings("serial")
public class DateSelector extends JPanel {
	private JComboBox selectorDay;
	private JComboBox selectorMonth;
	
	/**
	 * Creates new DateSelector with month and date selectors.
	 */
	public DateSelector() {
		selectorMonth = new JComboBox(Constants.MONTHS);
		selectorDay = new JComboBox(Util.arrayFill(1, Util.daysInMonth(selectorMonth.getSelectedIndex()+1)));
		
		selectorMonth.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            	// Update selectorDay to show correct amount of days for selected month.
            	int daysInMonth = Util.daysInMonth(selectorMonth.getSelectedIndex()+1);
            	if (selectorDay.getItemCount() != daysInMonth) {
            		selectorDay.setModel(new DefaultComboBoxModel(Util.arrayFill(1, daysInMonth)));
            		selectorDay.validate();
            	}
            }
		});

		setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
		add(selectorMonth);
		add(Box.createRigidArea(new Dimension(10, 0)));
		add(selectorDay);
		add(Box.createHorizontalGlue());
	}
	
	/**
	 * Returns currently selected date as DateTime.
	 * @return DateTime representation of currently selected date.
	 */
	public DateTime getDate() {
		return new DateTime(new DateTime().getYear(), 
							selectorMonth.getSelectedIndex()+1,
							selectorDay.getSelectedIndex()+1,
							0, 0, 0, 0);
	}
	
	/**
	 * Enables the combo box so that items can be selected. 
	 * When the combo box is disabled, items cannot be selected and 
	 * values cannot be typed into its field (if it is editable).
	 * @param b a boolean value, where true enables the component and false disables it
	 */
	@Override
	public void setEnabled(boolean b) {
		selectorMonth.setEnabled(b);
		selectorDay.setEnabled(b);
	}

}
